﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Waiter.Common
{
    class CommonLogging
    {
        public static void fsWriteLog(string type, string action, string param, string detail)
        {
            fsCreateLogFolder();
            string fileName = CommonUtils.fsFormatDate(CommonConstants.YYYYMMDD, DateTime.Now);
            fileName = Properties.Settings.Default.LOG_FOLDER_PATH + "\\" + fileName + ".log";
            StreamWriter w = new StreamWriter(fileName, true);
            w.Write("\n"
                + type 
                +" " 
                + DateTime.Now.ToString() 
                + "*******************************************************************************************\n");
            w.Write("##### " + action + " #####");
            w.Write("\n");
            w.Write(param);
            w.Write("\n");
            w.Write(detail);
            w.Flush();
            w.Close();
        }

        private static void fsCreateLogFolder()
        {
            try
            {
                if (!Directory.Exists(Properties.Settings.Default.LOG_FOLDER_PATH))
                {
                    Directory.CreateDirectory(Properties.Settings.Default.LOG_FOLDER_PATH);
                }
            }
            catch (Exception)
            {
                Properties.Settings.Default.LOG_FOLDER_PATH = "C:\\WaiterLog";
                Properties.Settings.Default.Save();
                fsCreateLogFolder();
            }
        }

        public static void fsDeleteUnUseLogFile()
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(Properties.Settings.Default.LOG_FOLDER_PATH);
                FileInfo[] files = dir.GetFiles();
                foreach (FileInfo f in files)
                {
                    try
                    {
                        DateTime createDate = f.CreationTime.AddDays(Properties.Settings.Default.LOG_TIME_STORE);
                        if (createDate < DateTime.Now)
                        {
                            f.Delete();
                        }
                    }
                    catch (Exception)
                    {
                    }
                    
                }
            }
            catch (Exception)
            {
            }
        }
    }
}
